<script setup lang="ts" name="CommunitySettings">
import {onActivated, ref, reactive} from 'vue'
import {ElMessage, ElMessageBox, FormRules} from 'element-plus'
import {
  HeaderData,
  Operation as Oper,
  RowOperbuttons
} from '@/components/dTable/dTable'
import {
  OperButton,
  SearchButton,
  SearchFromItem,
  SearchFromJustify
} from '@/components/dTable/dHeader'
import {
  PageConfig,
  defaultPage,
  defaultPageSize,
  defaultPageSizes,
  defaultLayout
} from '@/components/dTable/dFooter'
import {ColorTheme, ColorRed, DialogType} from '@/api/config'
import operation from '@/components/dTable/components/operation.vue'
import pageContainer from '@/components/pageContainer.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import addCommunity from './addCommunity.vue'
import {
  deleteTeam,
  getTeamList,
  TeamList,
  TeamParams
} from '@/api/publicHealthExamination/communitySettings'
import {NotLeadingAndTrailingSpaces} from '@/util/common'
//当前页面 表格数据 定义
const tableData = ref<Array<TeamList & RowOperbuttons>>([])

//显示加载状态
const showLoading = ref(false)

//表格头部数据定义
const tableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'name',
    label: '社区名称',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'leader',
    label: '负责人',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'phone',
    label: '联系电话',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'teamAddress',
    label: '地址',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'oper',
    label: '操作',
    columnType: 'slot',
    align: 'center',
    width: '90',
    fixed: 'right'
  }
])

//搜索项数据定义
const searchFromItems = ref<Array<SearchFromItem>>([
  {
    label: '社区名称',
    placeholder: '请输入社区名称',
    prop: 'name',
    type: 'input',
    enterSubmit: true
  }
])

const searchFromRules = reactive<FormRules>({
  name: [
    {
      required: false,
      message: '长度应不超过100个字符',
      max: 100,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入汉字、字母、数字、字符，首尾不能为空',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ]
})

//分页配置
const pageConfig = ref<PageConfig>({
  currentPage: defaultPage,
  pageSize: defaultPageSize,
  pageSizes: defaultPageSizes,
  total: 0,
  disabled: false,
  layout: defaultLayout
})

const searchFromData = reactive<TeamParams>({
  page: pageConfig.value.currentPage,
  limit: pageConfig.value.pageSize
})

//表头按钮
const operButtons = ref<Array<OperButton>>([
  {
    label: '新增',
    type: 'noraml',
    iconConfig: {icon: 'common-add', type: 'custom'},
    code: 'add'
  }
])

//表单靠左还是靠右
const searchFromJustify = ref<SearchFromJustify>('flexStart')

//搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([
  {type: 'search'},
  {type: 'clear'}
])

//操作按钮定义
const rowOperButtons: Array<Oper> = [
  {
    code: 'edit',
    label: '编辑',
    iconConfig: {
      icon: 'common-edit',
      type: 'custom',
      color: ColorTheme,
      size: 20
    }
  },
  {
    code: 'delete',
    label: '删除',
    iconConfig: {
      icon: 'common-delete',
      type: 'custom',
      color: ColorRed,
      size: 20
    }
  }
]

//后端数据拼接字段事件
const setTableData = (data: Array<TeamList>) => {
  const dataArr: Array<TeamList & RowOperbuttons> = []
  data.forEach((item) => {
    // 地址拼接
    item.teamAddress = (item.regionName || '') + (item.address || '')
    dataArr.push({...item, oper: rowOperButtons})
  })
  tableData.value = dataArr
}

//搜索数据事件
const searchData = (resetPage?: boolean) => {
  showLoading.value = true
  if (resetPage) pageConfig.value.currentPage = 1
  getTeamList({
    ...searchFromData,
    page: pageConfig.value.currentPage,
    limit: pageConfig.value.pageSize
  })
    .then((res) => {
      showLoading.value = false
      const {data} = res.data
      pageConfig.value.total = data.total === null ? 0 : data.total
      setTableData(data.records)
    })
    .catch((error) => {
      showLoading.value = false
      console.warn(error)
    })
}

//搜索事件
const onSubmit = () => {
  searchData(true)
}

//清除搜索栏数据事件
const clearForm = () => {
  searchData(true)
}

//清空搜索表单事件
const onFormClear = () => {
  clearForm()
}

//显示弹窗
const showDialog = ref(false)

//弹窗类型
const dialogType = ref<DialogType>('add')

// 初始化表单参数
const initTeamData = {
  name: '', //社区名称
  leader: '', // 负责人
  phone: '', // 联系电话
  address: '', // 详细地址
  districtCode: '', //行政区域编码
  parentCode: '', //上级行政区域编码
  provinceCode: '', //省级行政区域编码
  districtArr: []
}

//编辑的体检社区数据
const teamData = ref<TeamList>(initTeamData)

//操作按钮事件
const onOperation = (name: string) => {
  if (name === 'add') {
    teamData.value = {...initTeamData}
    dialogType.value = 'add'
    showDialog.value = true
  }
}

//关闭窗口事件
const onClose = () => {
  showDialog.value = false
  searchData()
}

//分页尺寸改变事件
const onSizeChange = () => {
  searchData(true)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData()
}

/**
 * @description: 编辑社区数据
 * @param {*} row
 * @return {*}
 */
const editCommunity = (row: TeamList) => {
  teamData.value = {
    id: row.id,
    name: row.name, //社区名称
    leader: row.leader, // 负责人
    phone: row.phone, // 联系电话
    address: row.address, // 详细地址
    districtCode: row.districtCode, //行政区域编码
    parentCode: row.parentCode, //上级行政区域编码
    provinceCode: row.provinceCode //省级行政区域编码
  }
  // 判断行政区域编码
  if (teamData.value.districtCode === teamData.value.provinceCode) {
    teamData.value.districtArr = [teamData.value.districtCode]
  } else {
    if (teamData.value.provinceCode === teamData.value.parentCode) {
      teamData.value.districtArr = [
        teamData.value.provinceCode,
        teamData.value.districtCode
      ]
    } else {
      teamData.value.districtArr = [
        teamData.value.provinceCode,
        teamData.value.parentCode,
        teamData.value.districtCode
      ]
    }
  }
  dialogType.value = 'edit'
  showDialog.value = true
}

/**
 * @description: 删除社区
 * @param {*} row // 行数据
 * @return {*}
 */
const deleteCommunity = (row: TeamList) => {
  ElMessageBox.confirm('是否确认删除此社区？', '删除确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      return deleteTeam({teamId: row.id})
    })
    .then(() => {
      ElMessage.success('删除成功')
      searchData(true)
    })
    .catch((error) => {
      console.warn(error)
    })
}

//操作插槽事件（编辑，删除）事件
const cellOperation = (name: string, row: TeamList) => {
  if (name === 'edit') {
    editCommunity(row)
  } else if (name === 'delete') {
    deleteCommunity(row)
  }
}

onActivated(() => {
  searchData()
})
</script>
<template>
  <page-container>
    <d-table-promote
      :label-width="70"
      :stripe="true"
      :show-loading="showLoading"
      :oper-buttons="operButtons"
      :table-data="tableData"
      :table-header-data="tableHeaderData"
      :page-config="pageConfig"
      :search-form-data="searchFromData"
      :search-rules="searchFromRules"
      :search-form-items="searchFromItems"
      :search-from-justify="searchFromJustify"
      :search-buttons="searchButtons"
      @form-submit="onSubmit"
      @form-clear="onFormClear"
      @operation="onOperation"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    >
      <template #oper="scope">
        <operation
          :row="scope.row"
          :col="scope.item"
          @opertion-click="cellOperation"
        />
      </template>
    </d-table-promote>
  </page-container>
  <add-community
    v-if="showDialog"
    :show-dialog="showDialog"
    :dialog-type="dialogType"
    :community-data="teamData"
    @close="onClose"
  />
</template>
<style scoped></style>
